const LoremIpsum = require("lorem-ipsum").LoremIpsum;
const config = require("../config.json");
const textList = require("../text.json");

exports.word = (req, res) => {
  let num = parseInt(req.params[0]);
  if (num > config.MAX_WORDS) num = config.MAX_WORDS;

  let lorem = new LoremIpsum().generateWords(num);
  if (req.params[1] === ",") {
    lorem = lorem.split(" ");
  }

  res.json({
    params: req.params,
    data: lorem,
  });
};

exports.wordChinese = (req, res) => {
  // 随机返回testList素组中的几个
  let num = parseInt(req.params[0]);
  if (num > config.MAX_PARAGRAPHS) num = config.MAX_PARAGRAPHS;

  res.json({
    params: req.params,
    data: getRandomArrayElements(textList, num),
  });
};

// 随机返回数组中几个元素的方法
function getRandomArrayElements(arr, count) {
  var shuffled = arr.slice(0),
    i = arr.length,
    min = i - count,
    temp,
    index;
  while (i-- > min) {
    index = Math.floor((i + 1) * Math.random());
    temp = shuffled[index];
    shuffled[index] = shuffled[i];
    shuffled[i] = temp;
  }
  return shuffled.slice(min);
}
